<?php
declare(strict_types=1);

namespace AdminBundle\Http\Controllers\Admin\V1;

use AdminBundle\Repositories\AdminRepository;
use Hyperf\Di\Annotation\Inject;
use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Exception\BusinessException;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use HyperfExt\Auth\AuthManager;
use AdminBundle\Services\AdminService;

class AdminController extends AbstractController
{
    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;

    /**
     * @Inject
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject
     * @var AdminService
     */
    protected $service;

    /**
     * index
     * 用户列表，用户管理
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function index()
    {
        $page = (int) $this->request->query('page', 1);
        $pageSize = (int) $this->request->query('page_size', 20);
        $username = $this->request->input('username');
        $filter = ['id' => ['<>', 1]];
        if (($username ?? 0) && $username) {
            $filter['username'] = ['like', '%'.$username.'%'];
        }

        $list = $this->service->getList($filter, $page, $pageSize);
        return $this->response->success($list);
    }

    /**
     * info()
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function info() {
        $user = $this->request->getAttribute('auth');
        $role = $this->request->getAttribute('user_role');
        $v = [
            "roles"=>$role,
            "avatar"=> $user->avatar ? $user->avatar : "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            "name"=> $user->username
        ];
        return $this->response->success($v);
    }

    /**
     * getInfo
     * 根据id获取单条记录信息
     * @return \Psr\Http\Message\ResponseInterface
     *
     */
    public function getInfo($id)
    {
        $info = $this->service->getInfo($id, ['id', 'account', 'username']);
        $data = [
            'info' => $info,
        ];

        return $this->response->success($data);
    }

    /**
     * getRoles
     * 获取绑定角色信息
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function getRoles()
    {
        $data = $this->service->getRolesList();

        return $this->response->success($data);
    }

    /**
     * store
     * 保存，新建、编辑都用该方法，区别是否有主键id
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Exception
     */
    public function store()
    {
        $reqParam = $this->request->inputs(['id', 'username', 'account', 'password', 'mobile', 'email', 'user_roles']);
        
        if ($reqParam['username'] ?? '') {
            if (empty($reqParam['username'])) {
                throw new BusinessException(ErrorCode::PARAMETER_ERROR, '昵称不能为空');
            }

            $where = ['username' => $reqParam['username']];
            if (isset($reqParam['id']) && $reqParam['id']) {
                $where['id'] = ['<>', $reqParam['id']];
            } else {
                unset($reqParam['id']);
            }
            if (AdminRepository::instance()->getCount($where)) {
                throw new BusinessException(ErrorCode::PARAMETER_ERROR, '昵称已存在');
            }
        }

        if (!($reqParam['account'] ?? '') || !$reqParam['account']) {
            throw new BusinessException(ErrorCode::PARAMETER_ERROR, '账号不能为空');
        }
        $where = ['account' => $reqParam['account']];
        if (isset($reqParam['id']) && $reqParam['id']) {
            $where['id'] = ['<>', $reqParam['id']];
        } else {
            unset($reqParam['id']);
        }
        if (AdminRepository::instance()->getCount($where)) {
            throw new BusinessException(ErrorCode::PARAMETER_ERROR, '账号已存在');
        }

        if ((!($reqParam['password'] ?? '') || !$reqParam['password']) && !($where['id'] ?? 0)) {
            throw new BusinessException(ErrorCode::PARAMETER_ERROR, '密码不能为空');
        }
        
        if (($reqParam['password'] ?? '') && $reqParam['password']) {
            $reqParam['password'] = password_hash($reqParam['password'], PASSWORD_DEFAULT);
        }

        $this->service->register($reqParam);

        return $this->response->success();
    }

    /**
     * destroy
     * 删除用户
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function destroy($id)
    {
        $this->service->deleteInfo($id);

        return $this->response->success('ok');
    }

    public function login()
    {
        $request = $this->request->inputs(['account', 'password']);

        $validator = $this->validationFactory->make(
            $request,
            [
                'account' => 'required',
                'password' => 'required',
            ],
            [
                'account.required' => '账号必填',
                'password.required' => '密码必填',
            ]
        );

        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new BusinessException(ErrorCode::PARAMETER_ERROR, $errorMessage);
        }

        $token = auth('adminapi')->attempt($request);
        return $this->response->success(['token' => $token]);
    }

    public function user()
    {
        return $this->response->success([
            'username'=> $this->request->getAttribute('auth')->username
        ]);

    }

    public function logout()
    {
        try {
            auth('adminapi')->logout();
        } catch (\Throwable $throwable) {
            throw new BusinessException(ErrorCode::SERVER_ERROR, '账号已退出！');
        }
        return $this->response->success(['status' => true]);
    }

    public function changePwd()
    {
        $request = $this->request->inputs(['oldPassword', 'passwordConfirmation']);

        $filter['id'] = $this->request->getAttribute('auth')->id;
        $validator = $this->validationFactory->make(
            $request,
            [
                'oldPassword' => 'required',
                'passwordConfirmation' => 'required',
            ],
            [
                'oldPassword.required' => '旧密码必须',
                'passwordConfirmation.required' => '新密码必须',
            ]
        );

        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new BusinessException(ErrorCode::PARAMETER_ERROR, $errorMessage);
        }
        
        $filter['old_password'] = $request['oldPassword'];
        $filter['password'] = $request['passwordConfirmation'];

        $this->service->changePwd($filter);

        return $this->response->success([], '修改密码成功');
    }

    /**
     * 获取管理员信息
     */
    public function profile()
    {
        $user = $this->request->getAttribute('auth');   
        $info = $this->service->getAdminInfo($user->id, ['id', 'username', 'avatar', 'mobile', 'email', 'last_login_ip', 'last_login_time', 'created_at']);
        $data = [
            'info' => $info,
        ];

        return $this->response->success($data);
    }

    public function saveProfile()
    {
        $reqParam = $this->request->inputs(['username', 'mobile', 'email']);
        $reqParam['id'] = $this->request->getAttribute('auth')->id;
        
        if ($reqParam['username'] ?? '') {
            if (empty($reqParam['username'])) {
                throw new BusinessException(ErrorCode::PARAMETER_ERROR, '昵称不能为空');
            }

            $where = [
                'username' => $reqParam['username'],
                'id' => ['<>',  $reqParam['id']]
            ];
            if (AdminRepository::instance()->getCount($where)) {
                throw new BusinessException(ErrorCode::PARAMETER_ERROR, '昵称已存在');
            }
        }

        $this->service->saveData($reqParam);

        return $this->response->success();
    }
}